import {
  request
} from "../../request/index.js"
import regeneratorRuntime from "../../lib/runtime/runtime.js"

Page({
  data: {
    tabs: [{
        id: 0,
        value: "综合",
        isActive: true
      },
      {
        id: 1,
        value: "销量",
        isActive: false
      },
      {
        id: 2,
        value: "价格",
        isActive: false
    }],
    goodsLists:[]
  },
  //接口要的参数
  QueryParams:{
    query:"",
    cid:"",
    pagenum:1,
    pagesize:10
  },
  //总页数
  totalPages:1,
  onLoad: function (options) {
    this.QueryParams.cid=options.cid;
    this.getGoodsList()
  },

  //获取商品列表数据
  async getGoodsList(){
    const res=await request({url:"goods/search",data:this.QueryParams})
    //获取总条数
    const total=res.total;
    //计算总页数
    this.totalPages=Math.ceil(total/this.QueryParams.pagesize);
    this.setData({
      goodsLists:[...this.data.goodsLists,...res.goods]
    })
    //数据请求回来之后需要手动关闭等待的效果
    wx.stopPullDownRefresh();
      
  },
  //标题的点击事件
  handletabsItemChange(e) {
    //获取被点击的标题索引
    const {
      index
    } = e.detail;
    //修改原数组
    let {
      tabs
    } = this.data;
    tabs.forEach((e, i) => {
      i === index ? e.isActive = true : e.isActive = false
    });
    this.setData({
      tabs
    })
  },

  //滚动条触底事件
  onReachBottom(){
    //判断还有没有下一页数据
    if(this.QueryParams.pagenum>=this.totalPages){
      wx.showToast({
        title: '没有下一页数据了',
        icon: 'none'
      });
        
    }else {
      //还有下一页数据
      this.QueryParams.pagenum++;
      this.getGoodsList();
    }
  },
  //下拉刷新
  onPullDownRefresh(){
    //重置数组
    this.setData({
      goodsLists:[]
    })
    //重置页码
    this.QueryParams.pagenum=1;
    //重新发送请求
    this.getGoodsList();
  }
})